package com.alias.DAO.interfaces.impl;


import com.alias.DAO.interfaces.CountryDAO;
import com.alias.HibernateUtil;
import com.alias.model.Country;
import com.alias.model.Employees;
import org.hibernate.Query;
import org.hibernate.Session;

import javax.swing.*;
import java.util.*;

public class CountryDAOEmpl implements CountryDAO {
    @Override
    public String getCountryById(int id) {
        Country country = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            country = (Country) session.load(Country.class, id);

        } catch (Exception e) {

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return country.getName();
    }

    @Override
    public Map<String, Integer> getCountyriesMap() {
        Map<String, Integer> countriesMap = new HashMap<String, Integer>();
        List<Country> countryList = new ArrayList<Country>();
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            countryList = session.createCriteria(Country.class).list();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка 'getAll'", JOptionPane.OK_OPTION);

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        for (Country c : countryList) {
            countriesMap.put(c.getName(), c.getId());
        }
        return countriesMap;
    }

    @Override
    public List<Employees> getEmployeesSet(String countryName) {
        List<Employees> employeesList = new ArrayList<Employees>();
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            Query query = session.createQuery(
                    " select b "
                            + " from Employees b INNER JOIN b.country countries"
                            + " where countries.name = :countryName "
            ).setString("countryName", countryName);
            employeesList = (List<Employees>) query.list();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка 'getAll'", JOptionPane.OK_OPTION);
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return employeesList;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
